package com.wjx.config.database;

import com.wjx.common.datasource.DataSourceContextHolder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 配置数据源
 * @Auther: wjx
 * @Date: 2019/3/15 10:11
 */
@Configuration
public class DataSourceConfig {


    /**
     * 写数据源
     *
     * @return
     */
    @Bean(DataSourceContextHolder.MASTER_DATABASE)
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDatabase() {
        return DataSourceBuilder.create().build();
    }


    /**
     * 读数据源
     *
     * @return
     */
    @Bean(DataSourceContextHolder.SLAVE_DATABASE)
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDatabase() {
        return DataSourceBuilder.create().build();
    }


    /**
     * 设置了动态数据源交给AOP处理
     * 这边使用AOP来管理数据源,设置为默认数据源
     *
     * @return
     */
    @Bean("dynamicDataSource")
    @Primary
    public DataSource dynamicDataSource() {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //设置默认数据源,如果没有设置数据源，采用此数据源
        dynamicDataSource.setDefaultTargetDataSource(masterDatabase());

        //设置多数据源
        Map<Object, Object> map = new ConcurrentHashMap<>();
        map.put(DataSourceContextHolder.MASTER_DATABASE, masterDatabase());
        map.put(DataSourceContextHolder.SLAVE_DATABASE, slaveDatabase());
        //设置目标数据源
        dynamicDataSource.setTargetDataSources(map);
        return dynamicDataSource;
    }

}
